package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
    /**
     * 每分钟检查一次是否存在超时未支付订单(下单超过15分钟未支付就代表超时，需要修改状态为已取消)
     */

    @Autowired
    private OrdersMapper ordersMapper;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void  processOutTimeOrder(){
        //1、查询数据库orders表，条件：待付款， 下单时间>当前时间-15分钟
        //select * from orders where status = 0 and order_time < 当前时间-15分钟
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT, time);
        //2、如果查询到了数据，代表存在超时未支付订单，需要修改订单的状态为“Status = 6”
        //update
        if (ordersList !=null && ordersList.size()>0){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("定单超时");
                orders.setCancelTime(LocalDateTime.now());
                ordersMapper.update(orders);
            });
        }

    }

    /**
     * 每天凌晨 1点检查一次订单表，查看是否存在"派送中"的订单，如果存在修改状态为”已完成“
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0 52 14 * * ?")
    public void processDeliveryOrder(){
        //1、查询数据库orders表：条件状态-为派送中。不查最近一小时的订单， 下单时间 < 当前时间 - 1h的单
        //select * from orders where status = 4 and order_time < 当前时间-1小时
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);

        if (ordersList !=null && ordersList.size()>0){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now().minusHours(1));
                ordersMapper.update(orders);
            });
        }
        //2、如果查询到了数据，代表存在超时未支付订单，需要修改订单状态的状态为“status = 5“
    }
}
